using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.Collections.Generic;
using PigeonCms;
using FredCK.FCKeditorV2;
using System.Globalization;

public partial class Controls_CommentsAdmin : PigeonCms.BaseModuleControl
{

    //protected DateTime ItemDate
    //{
    //    get
    //    {
    //        CultureInfo culture;
    //        DateTimeStyles styles;
    //        culture = CultureInfo.CreateSpecificCulture("it-IT");
    //        styles = DateTimeStyles.None;
    //        DateTime res;
    //        DateTime.TryParse(TxtItemDate.Text, culture, styles, out res);
    //        return res.Date;
            
    //    }
    //    set
    //    {
    //        TxtItemDate.Text = "";
    //        if (value != DateTime.MinValue)
    //            TxtItemDate.Text = value.ToShortDateString();
    //    }
    //}

    protected new void Page_Init(object sender, EventArgs e)
    {
        base.Page_Init(sender, e);

        if (this.BaseModule.DirectEditMode)
        {
            BtnCancel.OnClientClick = "closePopup();";
            //editRow(base.CurrItem.Id);

            //fck does not work inside fancybox>updatepanel(partial postpack)
            //var scriptManager = ScriptManager.GetCurrent(this.Page);
            //scriptManager.RegisterPostBackControl(BtnSave);
        }

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        LblOk.Text = "";
        LblErr.Text = "";

        if (this.BaseModule.DirectEditMode)
        {
            if (base.CurrentId == 0)
                throw new ArgumentException();
        }

        if (!Page.IsPostBack)
        {
            loadDropStatusFilter();
        }
        if (this.BaseModule.DirectEditMode)
        {
            editRow(base.CurrentId);
        }
    }

    protected void DropStatusFilter_SelectedIndexChanged(object sender, EventArgs e)
    {
        try { Grid1.DataBind(); }
        catch (Exception ex)
        {
            LblErr.Text = ex.Message;
        }
    }

    protected void TxtSearchFilter_TextChanged(object sender, EventArgs e)
    {
        try { Grid1.DataBind(); }
        catch (Exception ex)
        {
            LblErr.Text = ex.Message;
        }
    }

    protected void ObjDs1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
        //see http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx
        //for use generics with ObjDs TypeName
        var filter = new CommentFilter();

        if (DropStatusFilter.SelectedValue != "")
        {
            filter.FilterStatus = true;
            filter.Status = (CommentStatus)Enum.Parse(typeof(CommentStatus), DropStatusFilter.SelectedValue);
        }

        if (this.CurrentId > 0)
            filter.Id = this.CurrentId;

        e.InputParameters["filter"] = filter;
    }

    protected void Grid1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            editRow(int.Parse(e.CommandArgument.ToString()));
        }
        if (e.CommandName == "DeleteRow")
        {
            deleteRow(int.Parse(e.CommandArgument.ToString()));
        }
        //Enabled
        if (e.CommandName == "ImgEnabledOk")
        {
            setFlag(Convert.ToInt32(e.CommandArgument), false, "enabled");
            Grid1.DataBind();
        }
        if (e.CommandName == "ImgEnabledKo")
        {
            setFlag(Convert.ToInt32(e.CommandArgument), true, "enabled");
            Grid1.DataBind();
        }
    }

    protected void Grid1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
            Utility.AddGlyph(Grid1, e.Row);
    }

    protected void Grid1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var item = new PigeonCms.CommentItem();
            item = (PigeonCms.CommentItem)e.Row.DataItem;


            //Published
            if (item.Status == CommentStatus.Spam)
            {
                Image img1 = (Image)e.Row.FindControl("ImgEnabledOk");
                img1.Visible = true;
            }
            else
            {
                Image img1 = (Image)e.Row.FindControl("ImgEnabledKo");
                img1.Visible = true;
            }

        }
    }

    protected void BtnSave_Click(object sender, EventArgs e)
    {
        if (checkForm())
        {
            if (saveForm())
                MultiView1.ActiveViewIndex = 0;
        }
    }

    protected void BtnCancel_Click(object sender, EventArgs e)
    {
        LblErr.Text = "";
        LblOk.Text = "";
        MultiView1.ActiveViewIndex = 0;
    }

    protected void MultiView1_ActiveViewChanged(object sender, EventArgs e)
    {
        if (this.BaseModule.DirectEditMode)
        {
            //list view not allowed (in case of js hacking)
            if (MultiView1.ActiveViewIndex == 0)
                MultiView1.ActiveViewIndex = 1;

        }

        if (MultiView1.ActiveViewIndex == 0)    //list view
        {
            //Utility.SetDropByValue(DropNew, "");
        }
    }

    #region private methods

    private bool checkForm()
    {
        LblErr.Text = "";
        LblOk.Text = "";
        bool res = true;

        if (!string.IsNullOrEmpty(TxtAlias.Text))
        {
            var filter = new ItemsFilter();
            var list = new List<PigeonCms.Item>();

            filter.Alias = TxtAlias.Text;
            list = new ItemsManager<Item,ItemsFilter>().GetByFilter(filter, "");
            if (list.Count > 0)
            {
                if (this.CurrentId == 0)
                {
                    res = false;
                    LblErr.Text += "alias in use<br />";
                }
                else
                {
                    if (list[0].Id != this.CurrentId)
                    {
                        res = false;
                        LblErr.Text += "alias in use<br />";
                    }
                }
            }
        }
        return res;
    }

    private bool saveForm()
    {
        bool res = false;
        LblErr.Text = "";
        LblOk.Text = "";

        try
        {
            var o1 = new Item();

            if (CurrentId == 0)
            {
                form2obj(o1);
                o1 = new ItemsManager<Item, ItemsFilter>().Insert(o1);
            }
            else
            {
                o1 = new ItemsManager<Item, ItemsFilter>().GetByKey(CurrentId);  //precarico i campi esistenti e nn gestiti dal form
                form2obj(o1);
                new ItemsManager<Item, ItemsFilter>().Update(o1);
            }
            Grid1.DataBind();
            LblOk.Text = Utility.GetLabel("RECORD_SAVED_MSG");
            res = true;
        }
        catch (Exception e1)
        {
            LblErr.Text = Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString();
        }
        finally
        {
        }
        return res;
    }

    private void clearForm()
    {
        LblId.Text = "";
        LitItemType.Text = "";
        LblCreated.Text = "";
        LblUpdated.Text = "";
        ChkEnabled.Checked = true;
        TxtAlias.Text = "";
        foreach (KeyValuePair<string, string> item in Config.CultureList)
        {
            TextBox t1 = new TextBox();
            t1 = (TextBox)PanelTitle.FindControl("TxtTitle" + item.Value);
            t1.Text = "";

            FCKeditor t2 = new FCKeditor();
            t2 = (FCKeditor)PanelDescription.FindControl("TxtDescription" + item.Value);
            t2.Value = "";
        }
        PermissionsControl1.ClearForm();
    }

    private void form2obj(Item obj)
    {
        obj.Id = CurrentId;
        obj.Enabled = ChkEnabled.Checked;
        obj.TitleTranslations.Clear();
        obj.DescriptionTranslations.Clear();
        obj.CategoryId = int.Parse(DropCategories.SelectedValue);
        obj.Alias = TxtAlias.Text;

        if (CurrentId == 0)
            obj.ItemTypeName = LitItemType.Text;

        foreach (KeyValuePair<string, string> item in Config.CultureList)
        {
            TextBox t1 = new TextBox();
            t1 = (TextBox)PanelTitle.FindControl("TxtTitle" + item.Value);
            obj.TitleTranslations.Add(item.Key, t1.Text);

            FCKeditor t2 = new FCKeditor();
            t2 = (FCKeditor)PanelDescription.FindControl("TxtDescription" + item.Value);
            obj.DescriptionTranslations.Add(item.Key, t2.Value);
        }
        obj.ItemParams = FormBuilder.GetParamsString(obj.ItemType.Params, ItemParams1);
        string fieldsString = FormBuilder.GetParamsString(obj.ItemType.Fields, ItemFields1);
        obj.LoadCustomFieldsFromString(fieldsString);
        PermissionsControl1.Form2obj(obj);
    }

    private void obj2form(Item obj)
    {
        LblId.Text = obj.Id.ToString();
        LblUpdated.Text = obj.DateUpdated.ToString() + " by " + obj.UserUpdated;
        LblCreated.Text = obj.DateInserted.ToString() + " by " + obj.UserInserted;
        ChkEnabled.Checked = obj.Enabled;
        TxtAlias.Text = obj.Alias;
        Utility.SetDropByValue(DropCategories, obj.CategoryId.ToString());

        foreach (KeyValuePair<string, string> item in Config.CultureList)
        {
            //ItemType itemType = obj.ItemType;

            string sTitleTranslation = "";
            TextBox t1 = new TextBox();
            t1 = (TextBox)PanelTitle.FindControl("TxtTitle" + item.Value);
            obj.TitleTranslations.TryGetValue(item.Key, out sTitleTranslation);
            t1.Text = sTitleTranslation;

            string sDescriptionTraslation = "";
            FCKeditor t2 = new FCKeditor();
            t2 = (FCKeditor)PanelDescription.FindControl("TxtDescription" + item.Value);
            obj.DescriptionTranslations.TryGetValue(item.Key, out sDescriptionTraslation);
            t2.Value = sDescriptionTraslation;
        }
        ItemParams1.LoadParams(obj);
        ItemFields1.LoadFields(obj);
        PermissionsControl1.Obj2form(obj);
        LitItemType.Text = obj.ItemTypeName;
        
    }

    private void editRow(int recordId)
    {
        var obj = new PigeonCms.Item();
        LblOk.Text = "";
        LblErr.Text = "";

        clearForm();
        CurrentId = recordId;
        if (CurrentId == 0)
        {
            obj.ItemDate = DateTime.Now;
            obj.ValidFrom = DateTime.Now;
            obj.ValidTo = DateTime.MinValue;
            int defaultCategoryId = 0;
            int.TryParse(DropStatusFilter.SelectedValue, out defaultCategoryId);
            obj.CategoryId = defaultCategoryId;
            obj2form(obj);
            //LitItemType.Text = DropNew.SelectedValue;
        }
        else
        {
            obj = new ItemsManager<Item, ItemsFilter>().GetByKey(CurrentId);
            obj2form(obj);
        }
        MultiView1.ActiveViewIndex = 1;
    }

    private void deleteRow(int recordId)
    {
        LblOk.Text = "";
        LblErr.Text = "";

        try
        {
            new ItemsManager<Item, ItemsFilter>().DeleteById(recordId);
        }
        catch (Exception e)
        {
            LblErr.Text = e.Message;
        }
        Grid1.DataBind();
    }

    private void loadDropStatusFilter()
    {
        DropStatusFilter.Items.Clear();
        DropStatusFilter.Items.Add(
            new ListItem(Utility.GetLabel("LblStatus", "Status"), ""));
        foreach (string item in Enum.GetNames(typeof(CommentStatus)))
        {
            int value = (int)Enum.Parse(typeof(CommentStatus), item);
            ListItem listItem = new ListItem(item, value.ToString());
            DropStatusFilter.Items.Add(listItem);
        }
    }

    private void setFlag(int recordId, bool value, string flagName)
    {
        try
        {
            PigeonCms.Item o1 = new PigeonCms.Item();
            o1 = new ItemsManager<Item, ItemsFilter>().GetByKey(recordId);
            switch (flagName.ToLower())
            {
                case "enabled":
                    o1.Enabled = value;
                    break;
                default:
                    break;
            }
            new ItemsManager<Item, ItemsFilter>().Update(o1);
        }
        catch (Exception e1)
        {
            LblErr.Text = Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString();
        }
        finally { }
    }

    protected void moveRecord(int recordId, Database.MoveRecordDirection direction)
    {
        LblErr.Text = "";
        LblOk.Text = "";

        try
        {
            new ItemsManager<Item, ItemsFilter>().MoveRecord(recordId, direction);
            Grid1.DataBind();
            MultiView1.ActiveViewIndex = 0;
        }
        catch (Exception e1)
        {
            LblErr.Text = Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString();
        }
        finally { }
    }
    #endregion
}
